package com.atguigu.gmall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

    // @Bean 创建一个bean对象交给spring容器管理
    @Bean
    public CorsWebFilter corsWebFilter(){
        // 创建CorsConfiguration
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); //任意请求头
        corsConfiguration.addAllowedOrigin("*"); //任意域名
        corsConfiguration.addAllowedMethod("*"); //任意
        corsConfiguration.setAllowCredentials(true); //允许携带cookie

        // 需要CorsConfigurationSource 这个对象，实现当前接口的实现类UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 第一个参数表示路径，第二参数表示设置跨域的方式等信息
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        // 返回当前对象
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }
}
